﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using UtilsSharp;
using UtilsSharp.Shared.Standard;
using XiaoShuTong.Model;

namespace XiaoShuTong.Api.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class MemberController : ControllerBase
    {
        private readonly IFreeSql _freeSql;

        public MemberController(IFreeSql freeSql)
        {
            _freeSql = freeSql;
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="name"></param>
        /// <param name="pwd"></param>
        /// <param name="client"></param>
        /// <returns></returns>
        [HttpPost]
        public BaseResult<object> Login(MemberLoginDto memberDto)
        {
            var rst = new BaseResult<object>();
            var member = _freeSql.Select<Member>().Where(c => c.Name == memberDto.Name && c.Pwd == memberDto.Pwd.ToMd5()).First();
            if (member == null)
            {
                rst.SetError("用户名或密码不正确");
                return rst;
            }

            else if (member.ExprieTime < DateTime.Today)
            {
                rst.SetError("账号已经过期");
                return rst;
            }

            //记录登录日志
            MeberLoginlog meberLoginlog = new MeberLoginlog { MemberId = member.Id, ClientId = memberDto.ClinetId, CreatedOn = DateTime.Now };
            _freeSql.Insert(meberLoginlog).ExecuteAffrows();

            //判断登录的客户端
            var clients = _freeSql.Select<MemberClient>().Where(c => c.MemberId == member.Id).ToList();
            if (clients.Count == 0)
            {
                MemberClient memberClient = new MemberClient { MemberId = member.Id, ClientId = memberDto.ClinetId, CreatedOn = DateTime.Now };
                _freeSql.Insert(memberClient).ExecuteAffrows();
            }
            else
            {
                if (!clients.Any(c => c.ClientId == memberDto.ClinetId))
                {
                    rst.SetError("该电脑不被允许登录");
                    return rst;
                }
            }

            return rst;
        }
    }
}
